<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>碳排放计算器</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .history-item {
            cursor: pointer;
            margin-bottom: 5px;
        }
        .history-item:hover {
            background-color: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1 class="text-center">碳排放计算器</h1>
        <form id="carbonForm" class="mt-4">
            <div class="mb-3">
                <label for="processEmission" class="form-label">工艺排放 (吨):</label>
                <input type="number" class="form-control" id="processEmission" required>
            </div>
            <div class="mb-3">
                <label for="energyConsumption" class="form-label">能源消耗 (吨):</label>
                <input type="number" class="form-control" id="energyConsumption" required>
            </div>
            <div class="mb-3">
                <label for="resourceConsumption" class="form-label">资源消耗 (吨):</label>
                <input type="number" class="form-control" id="resourceConsumption" required>
            </div>
            <div class="mb-3">
                <label for="processFactor" class="form-label">工艺排放因子:</label>
                <input type="number" class="form-control" id="processFactor" value="0.22" required>
            </div>
            <div class="mb-3">
                <label for="energyFactor" class="form-label">能源消耗因子:</label>
                <input type="number" class="form-control" id="energyFactor" value="0.56" required>
            </div>
            <div class="mb-3">
                <label for="resourceFactor" class="form-label">资源消耗因子:</label>
                <input type="number" class="form-control" id="resourceFactor" value="0.33" required>
            </div>
            <button type="button" class="btn btn-primary w-100" id="calculateBtn">计算碳排放</button>
        </form>
        <div id="result" class="mt-4 text-center fs-5 fw-bold"></div>

        <h2 class="mt-5">历史记录</h2>
        <ul id="historyList" class="list-unstyled"></ul>

        <div class="d-flex gap-2 mt-4">
            <button class="btn btn-danger flex-grow-1" id="clearHistoryBtn">清除历史</button>
            <button class="btn btn-success flex-grow-1" id="saveHistoryBtn">保存历史</button>
        </div>
    </div>

    <!-- 引入 jQuery 和 Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function () {
            let history = [];

            // 计算碳排放
            $('#calculateBtn').click(function () {
                const processEmission = parseFloat($('#processEmission').val());
                const energyConsumption = parseFloat($('#energyConsumption').val());
                const resourceConsumption = parseFloat($('#resourceConsumption').val());
                const processFactor = parseFloat($('#processFactor').val());
                const energyFactor = parseFloat($('#energyFactor').val());
                const resourceFactor = parseFloat($('#resourceFactor').val());

                const totalCarbon = (processEmission * processFactor) +
                    (energyConsumption * energyFactor) +
                    (resourceConsumption * resourceFactor);

                $('#result').text(`总碳排放量: ${totalCarbon.toFixed(2)} 吨`);

                // 保存历史记录
                const timestamp = new Date().toLocaleString();
                const record = {
                    time: timestamp,
                    inputs: { processEmission, energyConsumption, resourceConsumption, processFactor, energyFactor, resourceFactor },
                    result: totalCarbon
                };
                history.unshift(record);
                updateHistory();
            });

            // 更新历史记录
            function updateHistory() {
                $('#historyList').empty();
                history.forEach((record, index) => {
                    const li = $(`<li class="history-item" data-index="${index}">${record.time}</li>`);
                    $('#historyList').append(li);
                });
            }

            // 点击历史记录显示详情
            $('#historyList').on('click', '.history-item', function () {
                const index = $(this).data('index');
                const record = history[index];
                alert(`时间: ${record.time}\n输入: ${JSON.stringify(record.inputs)}\n结果: ${record.result.toFixed(2)} 吨`);
            });

            // 清除历史记录
            $('#clearHistoryBtn').click(function () {
                history = [];
                updateHistory();
            });

            // 保存历史记录为 CSV 文件
            $('#saveHistoryBtn').click(function () {
                const headers = ["时间", "工艺排放 (吨)", "能源消耗 (吨)", "资源消耗 (吨)", "工艺排放因子", "能源消耗因子", "资源消耗因子", "总碳排放量 (吨)"];
                const rows = history.map(record => [
                    record.time,
                    record.inputs.processEmission,
                    record.inputs.energyConsumption,
                    record.inputs.resourceConsumption,
                    record.inputs.processFactor,
                    record.inputs.energyFactor,
                    record.inputs.resourceFactor,
                    record.result.toFixed(2)
                ]);

                const csvContent = "data:text/csv;charset=utf-8," +
                    headers.join(",") + "\n" +
                    rows.map(row => row.join(",")).join("\n");

                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "carbon_history.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            });
        });
    </script>
</body>
</html>